package org.ctstudio.common.utils;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;
import java.util.Arrays;

public class Base64Util {
  private static final Base64Util _instance = new Base64Util();

  public static Base64Util getInstance() {
    return _instance;
  }

  protected Base64Util() {
  }

  public boolean isBase64(String raw) {
    return Base64.isBase64(raw);
  }

  public String toBase64(byte[] bytes) {
    return Base64.encodeBase64String(bytes).replace('+', '-').replace('/', '_');
  }

  public String toBase64(String original, Charset charset) {
    return toBase64(original.getBytes(charset));
  }

  public byte[] fromBase64(String base64String) {
    return Base64.decodeBase64(base64String.replace('-', '+').replace('_', '/'));
  }

  public String fromBase64(String base64String, Charset charset) {
    return new String(fromBase64(base64String), charset);
  }

  public String longToBase64(long l) {
    byte[] bytes = ByteUtil.getInstance().long2Bytes(l);
    return toBase64(bytes);
  }

  public String longToBase64TrimZero(long l) {
    byte[] bytes = ByteUtil.getInstance().long2Bytes(l);
    int actualStart = 0;
    for (byte b : bytes) {
      if (b != 0) {
        break;
      }
      actualStart++;
    }
    if (actualStart > 0) {
      bytes = Arrays.copyOfRange(bytes, actualStart, bytes.length);
    }
    return toBase64(bytes);
  }

  public long base64ToLong(String base64String) {
    byte[] bytes = fromBase64(base64String);
    return ByteUtil.getInstance().bytes2Long(bytes);
  }
}
